<?php
session_start();
include 'config.php';
	define("DB_NAME",$DATABASE_NAME);
	define("DB_USER",$DATABASE_USER);
	define("DB_PASSWORD",$DATABASE_PASSWORD);
	define("DB_HOST",$DATABASE_HOST);
	define("RIGHTS_GUEST", 0);
	define("RIGHTS_USER",1);
	define("RIGHTS_OFFICER", 2);
	define("RIGHTS_ADMIN", 3);
	
if(file_exists("install.php")) {
?>
<script type="text/javascript">
<!--
window.location = "<?php echo $SITE_URL ?>install.php"
//-->
</script>
<?php
	exit;
}

if($_SESSION["change_password"] == 1 && $_SESSION["changing_password"] != 1) {
?>
<script type="text/javascript">
<!--
window.location = "<?php echo $SITE_URL ?>change_password.php"
//-->
</script>
<?php
	exit;
}

function complete_page_html() {
?>
</div>
<div id="footer">
<?php include "../footer.php" ?>
</div>
</div>
</body>
</html>
<?php
}

function get_user_id() {
	$login_id = explode("_",$_SESSION["login_id"]);
  return $login_id[0];
}

function get_player_id_from_user_id() {
	$sql = "SELECT * FROM users WHERE users_id = " . get_user_id() . ";";
	$result = mysql_query($sql);
    $myrow = mysql_fetch_row($result);
	if(mysql_num_rows($result) < 1) {
		return -1;
	}
  return get_player_id($myrow[1]);
}

function get_db_version() {
	$sql = "SELECT * from general_info;";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return 1;
	}
	$myrow = mysql_fetch_row($result);
  return $myrow[1];
}

function get_user_rights($required_rights) {
	$sql = "SELECT * from users WHERE users_id = " . get_user_id() . ";";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return 0;
	}
	$myrow = mysql_fetch_row($result);
	if($myrow[4] >= $required_rights) {
		return 1;
	}
  return 0;
}
	
function get_site_version() {
	$sql = "SELECT * from general_info;";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return 1;
	}
	$myrow = mysql_fetch_row($result);
  return $myrow[0];
}

function get_armory_update_limit() {
	$sql = "SELECT * from general_info;";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return 1;
	}
	$myrow = mysql_fetch_row($result);
  return $myrow[2];
}

function get_item_name($items_id) {
	$sql = "SELECT * from items WHERE items_id = '" . $items_id . "';";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return -1;
	}
    $myrow = mysql_fetch_row($result);
  return $myrow[1];
}

function get_item_id($items_name) {
	$sql = "SELECT * from items WHERE items_name = '" . $items_name . "';";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return -1;
	}
    $myrow = mysql_fetch_row($result);
  return $myrow[0];
}

function get_player_id($players_name) {
	$sql = "SELECT * from players WHERE players_name = '" . $players_name . "';";
	$result = mysql_query($sql);
    $myrow = mysql_fetch_row($result);
	if(mysql_num_rows($result) < 1) {
		return -1;
	}
  return $myrow[0];
}

function get_last_loot_index() {
	$sql = "SELECT * from loots ORDER BY loots_id DESC;";
	$result = mysql_query($sql);
	$myrow = mysql_fetch_row($result);
  return $myrow[0];
}

function add_player($players_name) {
	$sql = "INSERT into players (players_name) VALUES('" . strtolower($players_name) . "');";
	$result = mysql_query($sql);
	$salt = substr(uniqid(rand(), true), 0, 8);
	$salt = md5($salt);
	$sql = "INSERT into users (users_login,users_password,users_salt,users_rights) VALUES('" . strtolower($players_name) . "','" . md5($salt."temp") . "','" . $salt . "',1);";
	$result2 = mysql_query($sql);
}

function add_loot($loot_date,$loot_players_name,$loot_items_id) {
	$players_id = get_player_id($loot_players_name);
	if($players_id == -1) {
		add_player($loot_players_name);
		$players_id = get_player_id($loot_players_name);
	}
	$sql = "INSERT into loots (loots_date,players_id,items_id) VALUES('" . $loot_date . "'," . $players_id . "," . $loot_items_id . ");";
	$result = mysql_query($sql);
}

function get_item_data($items_id) {
	$sql = "SELECT * from items WHERE items_id = " . $items_id . ";";
	$result = mysql_query($sql);
	$myrow = mysql_fetch_row($result);
	if(mysql_num_rows($result) < 1) {
		return -1;
	}
  return $myrow;
}

function get_player_name($players_id) {
	$sql = "SELECT * from players WHERE players_id = " . $players_id . ";";
	$result = mysql_query($sql);
	if(mysql_num_rows($result) < 1) {
		return -1;
	}
    $myrow = mysql_fetch_row($result);
  return $myrow[1];
}

function load($url,$options=array('method'=>'get','return_info'=>false)) {
    $url_parts = parse_url($url);
    $info = array(//Currently only supported by curl.
        'http_code'    => 200
    );
    $response = '';
    
    $send_header = array(
        'Accept' => 'text/*',
        'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4'
    );

    ///////////////////////////// Curl /////////////////////////////////////
    //If curl is available, use curl to get the data.
    if(function_exists("curl_init") 
                and (!(isset($options['use']) and $options['use'] == 'fsocketopen'))) { //Don't user curl if it is specifically stated to user fsocketopen in the options
        if(isset($options['method']) and $options['method'] == 'post') {
            $page = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
        } else {
            $page = $url;
        }

        $ch = curl_init($url_parts['host']);

        curl_setopt($ch, CURLOPT_URL, $page);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Just return the data - not print the whole thing.
        curl_setopt($ch, CURLOPT_HEADER, true); //We need the headers
        curl_setopt($ch, CURLOPT_NOBODY, false); //The content - if true, will not download the contents
        if(isset($options['method']) and $options['method'] == 'post' and $url_parts['query']) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $url_parts['query']);
        }
        //Set the headers our spiders sends
        curl_setopt($ch, CURLOPT_USERAGENT, $send_header['User-Agent']); //The Name of the UserAgent we will be using ;)
        $custom_headers = array("Accept: " . $send_header['Accept'] );
        if(isset($options['modified_since']))
            array_push($custom_headers,"If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);

        curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt"); //If ever needed...
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        if(isset($url_parts['user']) and isset($url_parts['pass'])) {
            $custom_headers = array("Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
        }

        $response = curl_exec($ch);
        $info = curl_getinfo($ch); //Some information on the fetch
        curl_close($ch);

    //////////////////////////////////////////// FSockOpen //////////////////////////////
    } else { //If there is no curl, use fsocketopen
        if(isset($url_parts['query'])) {
            if(isset($options['method']) and $options['method'] == 'post')
                $page = $url_parts['path'];
            else
                $page = $url_parts['path'] . '?' . $url_parts['query'];
        } else {
            $page = $url_parts['path'];
        }

        $fp = fsockopen($url_parts['host'], 80, $errno, $errstr, 30);
        if ($fp) {
            $out = '';
            if(isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
                $out .= "POST $page HTTP/1.1\r\n";
            } else {
                $out .= "GET $page HTTP/1.0\r\n"; //HTTP/1.0 is much easier to handle than HTTP/1.1
            }
            $out .= "Host: $url_parts[host]\r\n";
            $out .= "Accept: $send_header[Accept]\r\n";
            $out .= "User-Agent: {$send_header['User-Agent']}\r\n";
            if(isset($options['modified_since']))
                $out .= "If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])) ."\r\n";

            $out .= "Connection: Close\r\n";
            
            //HTTP Basic Authorization support
            if(isset($url_parts['user']) and isset($url_parts['pass'])) {
                $out .= "Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']) . "\r\n";
            }

            //If the request is post - pass the data in a special way.
            if(isset($options['method']) and $options['method'] == 'post' and $url_parts['query']) {
                $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                $out .= 'Content-Length: ' . strlen($url_parts['query']) . "\r\n";
                $out .= "\r\n" . $url_parts['query'];
            }
            $out .= "\r\n";

            fwrite($fp, $out);
            while (!feof($fp)) {
                $response .= fgets($fp, 128);
            }
            fclose($fp);
        }
    }

    //Get the headers in an associative array
    $headers = array();

    if($info['http_code'] == 404) {
        $body = "";
        $headers['Status'] = 404;
    } else {
        //Seperate header and content
        $separator_position = strpos($response,"\r\n\r\n");
        $header_text = substr($response,0,$separator_position);
        $body = substr($response,$separator_position+4);
        
        foreach(explode("\n",$header_text) as $line) {
            $parts = explode(": ",$line);
            if(count($parts) == 2) $headers[$parts[0]] = chop($parts[1]);
        }
    }

    if($options['return_info']) return array('headers' => $headers, 'body' => $body, 'info' => $info);
    return $body;
}

function print_ar($array, $count=0) {
    $i=0;
    $tab ='';
    while($i != $count) {
        $i++;
        $tab .= "&nbsp;&nbsp;|&nbsp;&nbsp;";
    }
    foreach($array as $key=>$value){
        if(is_array($value)){
            echo $tab."[<strong><u>$key</u></strong>]<br />";
            $count++;
            print_ar($value, $count);
            $count--;
        }
        else{
            $tab2 = substr($tab, 0, -12);
            echo "$tab2~ $key: <strong>$value</strong><br />";
        }
        $k++;
    }
    $count--;
}

function dump(&$var, $info = FALSE) {
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';
 
    if($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix.rand().$suffix; $vname = FALSE;
    foreach($vals as $key => $val) if($val === $new) $vname = $key;
    $var = $old;

    echo "<pre style='margin: 0px 0px 10px 0px; display: block; background: white; color: black; font-family: Verdana; border: 1px solid #cccccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
    if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
    do_dump($var, '$'.$vname);
    echo "</pre>";
}

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL) {
    $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];
   
        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";
   
        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";

        $var = $var[$keyvar];
    }
}
?>


<?php
// run updates from the wowarmory each time the page loads.
	mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die(mysql_error());
	mysql_select_db(DB_NAME);

$myFile = "armory_items_updated.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
//$sql = "SELECT * FROM items ORDER BY items_last_update LIMIT " . get_armory_update_limit() . ";";
//$result2 = mysql_query($sql);
while($myrow2 = mysql_fetch_row($result2)) {
	$lookup_item=$myrow2[0];
	set_time_limit(60);
	$result_url = load('http://www.wowarmory.com/item-info.xml?i=' . $lookup_item);
	$xmlparser = xml_parser_create();
	$xmldata = $result_url;
	xml_parse_into_struct($xmlparser,$xmldata,$values);
	xml_parser_free($xmlparser);
	$xml_found = 0;
	for($x=0;$x<sizeof($values);$x++) {
		if($values[$x]['tag'] == "ITEM" && $values[$x]['type'] == "open" && $xml_found == 0) {
			$xml_found = $xml_found + 1;
			$items_id = $values[$x]['attributes']['ID'];
			$items_name = mysql_real_escape_string($values[$x]['attributes']['NAME']);
		}
		if($values[$x]['tag'] == "CREATURE") {
			$xml_found = $xml_found + 2;
			$npcs_id = $values[$x]['attributes']['ID'];
			$npcs_name = mysql_real_escape_string($values[$x]['attributes']['NAME']);
			$zone_name = mysql_real_escape_string($values[$x]['attributes']['AREA']);
		}
	}
	if($xml_found > 0) {
		if($xml_found == 1) {
			$npcs_id = "-99";
			$npcs_name = "-99";
			$zone_name = "-99";
		}
		$sql = "UPDATE items SET items_name='" . $items_name . "', npcs_id=" . $npcs_id . ", npcs_name='" . $npcs_name . "', zone_name='" . $zone_name . "', items_last_update='" . time() . "' WHERE items_id=" . $items_id . ";";
		$result = mysql_query($sql);
		$stringData = $items_id . " updated: " . date("m/d/y",time()) . "\r\n";
		fwrite($fh, $stringData);
	}
	else {
		$stringData = $items_id . " not found: " . date("m/d/y",time()) . "\r\n";
		fwrite($fh, $stringData);
	}
}
fclose($fh);
?>


